import {constantRoutes} from '@/router'
import Layout from '@/layout/index'
import MenuRegister from '@/router/menuRegister'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      path: route.url,
      component: route.parentId === '' ? Layout : MenuRegister[route.comName],
      alwaysShow: route.parentId === '',
      meta: {title: route.name, icon: route.icon, id: route.id, affix: route.affix},
      name: route.comName,
      hidden: route.hidden === 'Y'
    }

    if (route.children != null && route.children !== undefined && route.children.length > 0) {
      tmp.children = filterAsyncRoutes(route.children, roles)
    }
    res.push(tmp)
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({commit}, roles) {
    return new Promise(resolve => {
      const MenuInfo = [{
        "affix": false,
        "children": [],
        "comName": "",
        "filePath": "",
        "heddin": "",
        "hidden": "Y",
        "icon": "/",
        "id": "bbb460df-7046-49eb-922a-cf0c9a04aa79",
        "name": "系统接口权限配置",
        "parentId": "",
        "sort": 0,
        "url": "/system"
      }]
      const accessedRoutes = filterAsyncRoutes(MenuInfo, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
